const mysql = require('mysql2/promise');

// 数据库配置
const dbConfig = {
  host: 'localhost',
  user: 'root',
  password: '123456', // 使用您的实际密码
  database: 'chatime',
  port: 3306
};

async function setDefaultAvatars() {
  const pool = mysql.createPool(dbConfig);
  
  try {
    console.log('🔗 连接数据库...');
    await pool.getConnection();
    console.log('✅ 数据库连接成功');
    
    // 获取所有没有头像的用户
    console.log('📋 查询没有头像的用户...');
    const [users] = await pool.execute(`
      SELECT id, name FROM users WHERE avatar = '' OR avatar IS NULL
    `);
    
    console.log(`📊 找到 ${users.length} 个需要设置头像的用户`);
    
    if (users.length === 0) {
      console.log('✅ 所有用户都已经有头像了');
      return;
    }
    
    // 为每个用户设置默认头像
    console.log('🎨 为用户设置默认头像...');
    for (let i = 0; i < users.length; i++) {
      const user = users[i];
      const avatarNumber = (i % 12) + 1; // 循环使用avatar1到avatar12
      const avatarName = `avatar${avatarNumber}`;
      
      await pool.execute(`
        UPDATE users SET avatar = ? WHERE id = ?
      `, [avatarName, user.id]);
      
      console.log(`✅ 用户 ${user.name} (${user.id}) 设置为 ${avatarName}`);
    }
    
    console.log('\n🎉 所有用户的默认头像设置完成！');
    
    // 验证结果
    console.log('\n📋 验证结果...');
    const [result] = await pool.execute(`
      SELECT id, name, avatar FROM users ORDER BY name
    `);
    
    console.log('📊 用户头像分配情况：');
    result.forEach(user => {
      console.log(`  ${user.name}: ${user.avatar || '无头像'}`);
    });
    
  } catch (error) {
    console.error('❌ 设置默认头像失败:', error);
  } finally {
    await pool.end();
  }
}

// 运行脚本
setDefaultAvatars(); 